package com.ming.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by mqsi on 2022/5/20 10:52
 */
@Configuration
@ConditionalOnClass(DruidDataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource",
		matchIfMissing = true)
public class DruidDataSourceConfig {

	protected static DruidDataSource createDataSource(DataSourceProperties properties,
	                                                  Class<? extends DruidDataSource> type) {
		return properties.initializeDataSourceBuilder().type(type).build();
	}

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.druid")
	public DruidDataSource druidDataSource(DataSourceProperties dataSourceProperties){
		DruidDataSource dataSource = DruidDataSourceConfig.createDataSource(dataSourceProperties, DruidDataSource.class);
		DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(dataSourceProperties.determineUrl());
		String validationQuery = databaseDriver.getValidationQuery();
		if (validationQuery != null){
			dataSource.setTestOnBorrow(true);
			dataSource.setValidationQuery(validationQuery);
		}
		return dataSource;
	}

	@Bean
	public ServletRegistrationBean DruidStatViewServlet(){
		ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		bean.addInitParameter("loginUsername", "admin");
		bean.addInitParameter("loginPassword", "admin@123");
		return bean;
	}


	@Bean
	public FilterRegistrationBean DruidWebStatFilter(){
		FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
		bean.addUrlPatterns("/*");
		bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
		return bean;
	}

}
